/*
 * Copyright (c) 2021. Dylan Cai
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//package com.dylanc.longan.design

package com.gitee.wsl.android.ext

import android.os.CancellationSignal
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.ext.K
import com.gitee.wsl.ext.base.currentDateTime
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import timber.log.Timber
import kotlin.coroutines.CoroutineContext
import kotlin.system.measureNanoTime
import kotlin.system.measureTimeMillis


inline fun K.debugMeasureNanoTime(block: () -> Unit){
    if(application.isAppDebug){
        val id = currentDateTime.nanosecond
        Timber.d("$id measureNanoTime run start...")
        val runTime = measureNanoTime(block)
        Timber.d("$id run time:$runTime")
    }else
        block()
}

/**
 * LifecycleOwner
 */
inline fun K.launchAndRepeatOnLifecycleOwner(
    owner: LifecycleOwner,
    newCoroutineContext: CoroutineContext = Dispatchers.Main,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    crossinline block: suspend CoroutineScope.() -> Unit
) = owner.lifecycleScope.launch(newCoroutineContext) {
    owner.repeatOnLifecycle(minActiveState) {
        block()
    }
}

inline fun K.debugMeasureTimeMillis(block: () -> Unit) {
    if(application.isAppDebug){
        val id = currentDateTime.nanosecond
        Timber.d("$id measureTimeMillis run start...")
        val runTime = measureTimeMillis(block)
        Timber.d("$id run time:$runTime")
    }else
        block()
}

fun <T> K.launchWithCancellationSignal(
    cancellationSignal: CancellationSignal?,
    block: suspend CoroutineScope.() -> T
): T {
    return kotlinx.coroutines.runBlocking {
        val deferred = async(block = block)
        cancellationSignal?.setOnCancelListener {
            deferred.cancel()
        }
        deferred.await()
    }
}